<template>
  <div id="box">
    <!--修改信息-->
    <el-row>
      <el-col :offset="2" :span="10">
        <el-card class="empInfo">
          <div slot="header" class="clearfix"><span>修改个人信息</span></div>
          <el-form label-position="right" :model="emp" ref="emp" :rules="infoRules">
            <!--用户名不可以修改-->
            <el-form-item label="头像" :label-width="formLabelWidth">
              <el-row>
                <el-col>
                  <span class="header-style"><img :src="emp.empImg"></span>
                  <div class="button-style">
                    <el-upload :multiple="false" :show-file-list="false" :action="upload"
                               :file-list="fileList" :on-success="upload_success" list-type="picture">
                      <el-button size="small" style="margin-top: 5px" type="primary">编辑头像</el-button>
                    </el-upload>
                  </div>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="用户名" :label-width="formLabelWidth">{{emp.empName}}</el-form-item>
            <el-form-item label="员工性别" prop="empSex" :label-width="formLabelWidth">
              <el-radio disabled v-model="emp.empSex" label="男">男</el-radio>
              <el-radio disabled v-model="emp.empSex" label="女">女</el-radio>
            </el-form-item>
            <el-form-item label="手机号码" :label-width="formLabelWidth" prop="empTel">
              <el-input v-model="emp.empTel" style="width:300px" autocomplete="off" ></el-input>
            </el-form-item>
            <el-form-item label="所属部门" :label-width="formLabelWidth">
              <!--key绑定主键，要和select的value-key属性对应，引用字段名要一致，label用于显示内容，value值用来包含对象，用于提交-->
              <el-select :disabled="true" v-model="emp.department" @change="selectDeptJob(emp)" value-key="deptId" style="width: 300px;"
                         placeholder="请选择所属部门">
                <el-option v-for="department in deptData" :key="department.deptId"
                           :label="department.deptName" :value="department"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="职位" :label-width="formLabelWidth">
              <el-select :disabled="true" v-model="emp.job.jobName" value-key="jobId" style="width: 300px;" placeholder="请选择职位">
                <el-option v-for="job in deptJobData" :key="job.jobId"
                           :label="job.jobName" :value="job"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item >
              <el-row>
                <el-col :offset="10">
                  <el-button type="primary" @click="saveEmpInfo">保存</el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="empInfo">
          <div slot="header" class="clearfix"><span>修改密码</span></div>
          <el-form class="user-account-key" ref="form" :model="form" :rules="rules" :label-width="formLabelWidth">
            <el-form-item label="原密码" prop="password">
              <el-input type="password" placeholder="请输入原密码" v-model="form.password" style="width:300px" show-password></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input type="password" placeholder="请设置新密码" v-model="form.newPassword" style="width:300px" show-password></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="newPassword2">
              <el-input type="password" placeholder="请确认新密码" v-model="form.newPassword2" style="width:300px" show-password></el-input>
            </el-form-item>
            <el-form-item>
              <el-row>
                <el-col :offset="4" style="margin-top: 211px">
                  <el-button type="primary" @click="savePwd('form')">保存</el-button>
                  <el-button @click="$refs['form'].resetFields()">重置</el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// eslint-disable-next-line no-unused-vars
var formData = new FormData() // 声明一个FormData对象
// eslint-disable-next-line no-redeclare
var formData = new window.FormData() // vue 中使用 window.FormData(),否则会报 'FormData isn't definded'
export default {
  data: function () {
    // 此处即表单发送之前验证
    var validatePassword = (rule, value, callback) => {
      if (value !== this.emp.empPwd) {
        callback(new Error('原密码错误'))
      } else if (value.length > 12 || value.length < 6) {
        callback(new Error('密码长度必须在6-12位'))
      } else {
        callback()
      }
    }
    var validateNewPassword = (rule, value, callback) => {
      if (value === this.form.password) {
        callback(new Error('新密码不能与原密码相同'))
      } else if (value.length > 12 || value.length < 6) {
        callback(new Error('密码长度必须在6-12位'))
      } else {
        callback()
      }
    }
    var validateNewPassword2 = (rule, value, callback) => {
      if (value !== this.form.newPassword) {
        callback(new Error('与新密码不一致!'))
      } else if (value.length > 12 || value.length < 6) {
        callback(new Error('密码长度必须在6-12位'))
      } else {
        callback()
      }
    }
    return {
      valueUrl: '',
      imgSrc: '',
      userPhoto: '',
      fileList: [],
      upload: 'http://122.51.140.72:12345/upload',
      dialogVisible: false,
      formLabelWidth: '100px',
      emp: {
        empId: '',
        empImg: '',
        empName: '',
        empSex: '',
        empTel: '',
        department: {
          deptId: '',
          deptName: ''
        },
        job: {
          jobId: '',
          jobName: ''
        }
      },
      deptJobData: [],
      deptData: [],
      form: {
        password: '',
        newPassword: '',
        newPassword2: ''
      },
      infoRules: {
        empTel: [{
          required: true,
          message: '请输入电话号码'
        },
        {
          pattern: /^1[3|4|5|7|8|9][0-9]\d{8}$/,
          message: '手机号码格式不对'
        }]
      },
      rules: {
        password: [{
          required: true,
          message: '请输入原密码',
          trigger: 'blur'
        },
        {
          validator: validatePassword,
          trigger: 'blur'
        }
        ],
        newPassword: [{
          required: true,
          message: '请设置新密码',
          trigger: 'blur'
        },
        {
          validator: validateNewPassword,
          trigger: 'blur'
        }
        ],
        newPassword2: [{
          required: true,
          message: '请确认新密码',
          trigger: 'blur'
        },
        {
          validator: validateNewPassword2,
          trigger: 'blur'
        }
        ]
      }
    }
  },
  methods: {
    initData () {
      this.$axios.get('http://localhost:8088/emp')
        .then(v => {
          this.emp = v.data
          /* if(this.emp.empSex === '男'){
            this.imgSrc = '../assets/man.png'
          }else if(this.emp.empSex === '女'){
            this.imgSrc = '../assets/woman.png'
          } */
          this.selectDeptJob(this.emp)
        })
        .catch(function (v) {})
    },
    initDeptData () {
      this.$axios.get('http://localhost:8088/dept-list')
        .then(v => {
          this.deptData = v.data
        })
        .catch(function (v) {})
    },
    selectDeptJob (val) {
      this.$axios.get('http://localhost:8088/dept-job-list', {
        params: {
          deptId: val.department.deptId
        }
      })
        .then(v => {
          this.deptJobData = v.data
        }).catch()
    },
    saveEmpInfo () {
      this.$refs.emp.validate(valid => {
        if (valid) {
          this.$axios.post('http://localhost:8088/save-emp', this.emp)
            .then(v => {
              this.initData()
              this.$message({
                type: 'success',
                message: '修改信息成功'
              })
            }).catch()
        } else {
          this.$message.error('请正确填写员工信息！')
          return false
        }
      })
    },
    savePwd (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.emp.empPwd = this.form.newPassword
          this.$axios.post('http://localhost:8088/save-emp', this.emp)
            .then(v => {
              this.$message({
                type: 'success',
                message: '修改密码成功,即将跳转到登录页面'
              })
              this.startDivi()
            }).catch()
        } else {
          this.$message.error('请正确填写表单')
          return false
        }
      })
    },
    startDivi () {
      const TIME_COUNT = 3
      if (!this.timer) {
        this.count = TIME_COUNT
        this.show = false
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--
          } else {
            this.show = true
            clearInterval(this.timer)
            this.timer = null
            // 跳转的页面写在此处
            this.$router.push({
              path: '/login'
            })
          }
        }, 1000)
      }
    },
    // 选择文件后,立即预览文件
    /* uploadFile(el) {
      if (!el.target.files[0].size) return; // 如果文件大小为0，则返回
      if (el.target.files[0].type.indexOf('image') === -1) { //如果不是图片格式
        // this.$dialog.toast({ mes: '请选择图片文件' });
        console.log('请选择图片文件');
      } else {
        const that = this;
        const reader = new FileReader(); // 创建读取文件对象
        reader.readAsDataURL(el.target.files[0]); // 发起异步请求，读取文件
        reader.onload = function() {
          // 读取完成后，将结果赋值给img的src
          that.valueUrl = this.result;
          window.console.log(this.result);
        };
      }
    }, */
    // 上传文件
    /* submits() {
      //获取文件域中的文件对象，封装成formData参数
      formData.append('file', document.querySelector('input[type=file]').files[0]);
      window.console.log(formData);

      this.$axios.post("http://localhost:8088/upload", formData)
        .then(res => {
          this.imgSrc = "/" + res.data;
          this.dialogVisible = false;
          this.initData()
        }).catch()
    }, */
    // eslint-disable-next-line camelcase
    upload_success (response, file, flie_list) {
      console.log(file.response)/* 图片路径 */
      this.emp.empImg = file.response
      this.changeImg()
    },
    /* 提交路径到后台 */
    changeImg () {
      this.$axios.post('http://localhost:8088/save-emp', this.emp)
        .then(v => {
          this.$message({
            type: 'success',
            message: '已保存'
          })
          this.initData()
        }).catch()
    }
  },
  created () {
    this.initData()
    this.initDeptData()
  }
}
</script>

<style scoped>
  .empInfo{
    width: 500px;
    height: 600px;
  }
  img{
    border-radius: 40px;
  }
  .file {
    position: relative;
    display: inline-block;
    background: #409EFF;
    border: 1px solid #99D3F5;
    border-radius: 4px;
    padding: 2px 8px;
    overflow: hidden;
    margin-top: 20px;

    font-size: 13px;
    /* 字体颜色 */
    color: white;
    text-decoration: none;
    text-indent: 0;
    line-height: 20px;
  }
  .file input {
      position: absolute;
      right: 0;
      top: 0;
      opacity: 0;
  }
  .file:hover {
      background: #AADFFD;
      border-color: #78C3F3;
      color: #004974;
      text-decoration: none;
  }
  .clearfix{
    font-size: 20px;
  }
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both
  }
  .header-style{
    display: inline-block;
    width: 50px;
    height: 50px;
  }
  .button-style{
    position: absolute;
    top:0px;
    left: 70px;
  }
</style>
